const express = require('express');
const router = express.Router();
const pool = require('./db.js');
const { decryptForUser, generateUsernameHash } = require('./userDataEncryption.js'); // 导入解密和哈希函数

// 检查课程编号是否已存在（无需修改）
router.get('/check-course-code', async (req, res) => {
    const { courseCode } = req.query;
    try {
        const [rows] = await pool.execute('SELECT * FROM courses WHERE course_code =?', [courseCode]);
        res.json({ exists: rows.length > 0 });
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 创建课程（无需修改）
router.post('/create-course', async (req, res) => {
    const { courseName, courseCode, syllabus, teachingObjectives, assessmentMethod, teacherUserId, credits, study_period, place, course_time, teach_weeks } = req.body;

    try {
        await pool.execute('INSERT INTO courses (course_name, course_code, syllabus, teaching_objectives, assessment_method, teacher_user_id, credits, study_period, place, course_time, teach_weeks) VALUES (?,?,?,?,?,?,?,?,?,?,?)', [courseName, courseCode, syllabus, teachingObjectives, assessmentMethod, teacherUserId, credits, study_period, place, course_time, teach_weeks]);
        res.json({ message: '课程创建成功' });
    } catch (error) {
        console.error('Error creating course:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 获取课程接口（需要修改）
router.get('/get-courses', async (req, res) => {
    try {
        // 1. 获取课程和加密的教师信息
        const [rows] = await pool.execute(`
            SELECT courses.*, users.name as teacher_name, users.user_id as teacher_user_id
            FROM courses
            JOIN users ON courses.teacher_user_id = users.user_id
        `);
        
        // 2. 解密教师姓名
        const decryptedCourses = await Promise.all(rows.map(async course => {
            try {
                const decryptedTeacherName = course.teacher_name ? 
                    decryptForUser(course.teacher_user_id, course.teacher_name) : '';
                
                return {
                    ...course,
                    teacher_name: decryptedTeacherName
                };
            } catch (error) {
                console.error(`解密教师姓名失败 (用户ID: ${course.teacher_user_id}):`, error);
                return {
                    ...course,
                    teacher_name: '未知教师'
                };
            }
        }));
        
        res.json(decryptedCourses);
    } catch (error) {
        console.error('Error getting courses:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 获取单个课程详细信息接口（需要修改）
router.get('/get-course/:courseCode', async (req, res) => {
    const courseCode = req.params.courseCode;
    try {
        // 1. 获取课程和加密的教师信息
        const [rows] = await pool.execute(`
            SELECT courses.*, users.name as teacher_name, users.user_id as teacher_user_id
            FROM courses
            JOIN users ON courses.teacher_user_id = users.user_id
            WHERE courses.course_code =?
        `, [courseCode]);
        
        if (rows.length === 0) {
            return res.status(404).json({ message: '课程未找到' });
        }
        
        const course = rows[0];
        
        // 2. 解密教师姓名
        try {
            const decryptedTeacherName = course.teacher_name ? 
                decryptForUser(course.teacher_user_id, course.teacher_name) : '';
            
            res.json({
                ...course,
                teacher_name: decryptedTeacherName
            });
        } catch (error) {
            console.error(`解密教师姓名失败 (用户ID: ${course.teacher_user_id}):`, error);
            res.json({
                ...course,
                teacher_name: '未知教师'
            });
        }
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 获取所有已选课程（需要修改）
router.get('/get-selected-courses', async (req, res) => {
    const username = req.query.username;
    try {
        // 1. 使用用户名哈希查询用户ID
        const usernameHash = generateUsernameHash(username);
        const [userRows] = await pool.execute(
            'SELECT user_id FROM users WHERE username_hash =?', 
            [usernameHash]
        );
        
        if (userRows.length === 0) {
            return res.status(404).json({ message: '用户未找到' });
        }
        
        const studentId = userRows[0].user_id;

        // 2. 获取已选课程
        const [rows] = await pool.execute(`
            SELECT courses.*
            FROM courses
            JOIN course_selection ON courses.course_code = course_selection.course_code
            WHERE course_selection.student_id =?
        `, [studentId]);
        
        res.json(rows);
    } catch (error) {
        console.error('Error getting selected courses:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 选择课程（无需修改）
router.post('/select-course', async (req, res) => {
    const { student_id, course_code } = req.body;
    try {
        await pool.execute('INSERT INTO course_selection (student_id, course_code) VALUES (?,?)', [student_id, course_code]);
        res.json({ message: '选课成功' });
    } catch (error) {
        console.error('Error selecting course:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 获取教师创建的课程（需要修改）
router.post('/get-my-courses', async (req, res) => {
    const { username } = req.body;
    try {
        // 1. 使用用户名哈希查询用户ID
        const usernameHash = generateUsernameHash(username);
        const [userRows] = await pool.execute(
            'SELECT user_id FROM users WHERE username_hash =?', 
            [usernameHash]
        );
        
        if (userRows.length === 0) {
            return res.status(404).json({ message: '用户未找到' });
        }
        
        const teacherUserId = userRows[0].user_id;

        // 2. 获取教师创建的课程
        const [rows] = await pool.execute(
            'SELECT * FROM courses WHERE teacher_user_id =?', 
            [teacherUserId]
        );
        
        res.json(rows);
    } catch (error) {
        console.error('Error getting teacher courses:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 获取教师姓名接口（需要修改）
router.get('/get-teacher-name/:teacherId', async (req, res) => {
    const teacherId = req.params.teacherId;
    try {
        // 1. 获取加密的用户名
        const [rows] = await pool.execute(
            'SELECT username FROM users WHERE user_id =?', 
            [teacherId]
        );
        
        if (rows.length === 0) {
            return res.status(404).json({ message: '教师信息未找到' });
        }
        
        // 2. 解密用户名
        try {
            const encryptedUsername = rows[0].username;
            const decryptedUsername = decryptForUser(teacherId, encryptedUsername);
            res.json({ teacherName: decryptedUsername });
        } catch (error) {
            console.error(`解密教师姓名失败 (用户ID: ${teacherId}):`, error);
            res.json({ teacherName: '未知教师' });
        }
    } catch (error) {
        console.error('Error getting teacher name:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 退选课程接口（无需修改）
router.post('/drop-course', async (req, res) => {
    const { student_id, course_code } = req.body;
    try {
        // 第一步：根据 course_code 在 practice 表中找到所有相关的 practice_id
        const [practiceRows] = await pool.execute('SELECT practice_id FROM practice WHERE course_code =?', [course_code]);
        const practiceIds = practiceRows.map(row => row.practice_id);

        // 第二步：根据 student_id 和每个 practice_id 删除相关提交内容
        for (const practiceId of practiceIds) {
            // 删除 commited_choice_question 表中的记录
            await pool.execute('DELETE FROM commited_choice_question WHERE practice_id =? AND commit_user_id =?', [practiceId, student_id]);
            // 删除 commited_essay_question 表中的记录
            await pool.execute('DELETE FROM commited_essay_question WHERE practice_id =? AND commit_user_id =?', [practiceId, student_id]);
            // 删除 commited_fill_question 表中的记录
            await pool.execute('DELETE FROM commited_fill_question WHERE practice_id =? AND commit_user_id =?', [practiceId, student_id]);
            // 删除 commited_practice 表中的记录
            await pool.execute('DELETE FROM commited_practice WHERE practice_id =? AND commit_user_id =?', [practiceId, student_id]);
            // 删除 incorrect_question 表中的记录
            await pool.execute('DELETE FROM incorrect_question WHERE practice_id =? AND user_id =?', [practiceId, student_id]);
        }

        // 第三步：删除 course_selection 表中的选课记录
        const [result] = await pool.execute('DELETE FROM course_selection WHERE student_id =? AND course_code =?', [student_id, course_code]);

        if (result.affectedRows > 0) {
            res.json({ message: '退选课程成功，相关练习记录已清理' });
        } else {
            res.json({ message: '未找到该选课记录，退选失败' });
        }
    } catch (error) {
        console.error('Error dropping course:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

module.exports = router;